
import React, {Component} from 'react'
import { Upload, Icon, Modal,message } from 'antd';
import {reqDeleteImg} from '../../api'

export default class PicturesWall extends Component {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
  };

  getImgs = ()=>{
    return this.state.fileList.map(file=>file.name)
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleChange = async ({file,fileList}) => {
    //每次上传的图片位于filelist的最后1个file
    if(file.status==='done'){
      file = fileList[fileList.length-1]
      const {name,url} = file.response.data
      file.name = name
      file.url = url
    }
    else if(file.status==='removed'){
      const result = await reqDeleteImg(file.name)
      if(result.status===0){
        message.success('Image has been removed')
      }else{
        message.error('Image cannot be removed')
      }
    }
    this.setState({
      fileList
    })
  }

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <div>
        <Upload
          action="/manage/img/upload"
          listType="picture-card"
          fileList={fileList}
          name='image'
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 3 ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}


/*
fileList: [{
      uid: '-1',
      name: 'xxx.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    }]
*/